from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import train_test_split,GridSearchCV
import numpy as np
np.random.seed(666)

data=load_iris()
x=data.data
y=data.target

train_x,test_x,train_y,test_y=train_test_split(x,y)

knn=KNeighborsClassifier()
# n_neighbors:定义k  即以最近的k个点投票
# uniform:曼哈顿距离
# distans：欧式距离
pg={
    'n_neighbors':[2,3,4,5],
    'weights':['uniform','distance']
}

model=GridSearchCV(knn,pg,cv=5)
model.fit(train_x,train_y)

print(model.best_score_)
print(model.best_params_)

knn=KNeighborsClassifier(n_neighbors=5,weights='uniform')
knn.fit(train_x,train_y)

print('模型评分',model.score(test_x,test_y))
print('每个类别的预测概率',model.predict_proba(test_x))